package com.hisense.ovcloud.apicontrol.service;

import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONUtil;
import com.hisense.ovcloud.apicontrol.config.Constants;
import com.hisense.ovcloud.apicontrol.dto.req.ValidateReq;
import com.hisense.ovcloud.apicontrol.errors.ResForGW;
import com.hisense.ovcloud.apicontrol.errors.SystemError;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Optional;

@Service
@Slf4j
public class PuidCheckService extends BaseAGService{
    @Value("${puidCheck.ignores:save_bind_relation,get_wifi_device_list,get_wifi_config,get_device_wifi_config,appliance_register,get_device_type_info}")
    private String puidCheckIgnores;

    /**
     * PUID检查开关
     * 0：关闭
     * 1：打印ERROR日志，接口正常放行
     * 2：打印ERROR日志，接口报错
     * 默认: 1
     */
    @Value("${puidCheck.puidCheckSwitch:1}")
    private int puidCheckSwitch;

    @Value("${puidCheck.version:8.0}")
    private String puidCheckVersion;

    private boolean mustDoPuidChecks(String uri) {
        return Arrays.stream(puidCheckIgnores.split(",")).noneMatch(uri::contains);
    }

    public Mono<ResForGW> run(ValidateReq r, LinkedHashMap<String, Object> parametersMap) {
        ResForGW res = ResForGW.builder().build();
        double apiVersion = 0.0;
        if (parametersMap.containsKey(Constants.VERSION)) {
            apiVersion = Double.parseDouble(Optional.ofNullable(getFromParametersMap(parametersMap, Constants.VERSION)).orElse("0.0"));
        }

        if (apiVersion >= Double.parseDouble(puidCheckVersion) && mustDoPuidChecks(r.getPath())) {
            if (parametersMap.keySet().stream().anyMatch(x -> x.equalsIgnoreCase("wifiid"))) {
                res = setErrorResponse(res, SystemError.PUID_CHECK_FAILED_NO_WIFIID_PERMITED);
            }
        }

        if (res.getResultCode() != Constants.RESULT_CODE_SUCCESS) {
            switch (puidCheckSwitch) {
                case Constants.PuidCheck.CLOSED:
                    res = ResForGW.builder().build();
                    break;
                case Constants.PuidCheck.PRINT_LOG_LET_REQUEST_GO:
                    res = ResForGW.builder().build();
                    log.error("{} cannot contain wifiid after version {}: {}", r.getPath(), puidCheckVersion, JSONUtil.toJsonStr(parametersMap, new JSONConfig().setIgnoreNullValue(false)));
                    break;
                case Constants.PuidCheck.PRINT_LOG_LET_REQUEST_DOWN:
                    log.error("{} cannot contain wifiid after version {}: {}", r.getPath(), puidCheckVersion, JSONUtil.toJsonStr(parametersMap, new JSONConfig().setIgnoreNullValue(false)));
            }
        }
        return Mono.just(res);
    }
}
